package com.leyou.gateway.filters;

import com.leyou.common.auth.dto.Payload;
import com.leyou.common.auth.dto.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 虎哥
 */
@Slf4j
@Component
@EnableConfigurationProperties(JwtProperties.class)
@ConfigurationProperties("ly.filter")
public class AuthFilter extends ZuulFilter {

    private List<String> allowPaths;

    @Autowired
    private JwtProperties jwtProp;

    public List<String> getAllowPaths() {
        return allowPaths;
    }

    public void setAllowPaths(List<String> allowPaths) {
        this.allowPaths = allowPaths;
    }

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    /**
     * 是否执行run方法。
     */
    @Override
    public boolean shouldFilter() {
        // 1.获取Request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 2.获取当前路径
        String path = request.getRequestURI();
        // 3.判断是否在白名单中
        for (String allowPath : allowPaths) {
            if(path.startsWith(allowPath)){
                // 说明这个路径是白名单中的一个
                return false;
            }
        }
        // 不是白名单中的路径，则应该返回true
        return true;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 业务逻辑
     */
    @Override
    public Object run() throws ZuulException {
        // 1.获取Request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        try {
            // 	2.获取cookie中的token
            String token = CookieUtils.getCookieValue(request, jwtProp.getUser().getCookieName());
            //	3.验证token，获取用户
            //		3.1.公钥解析验证
            Payload<UserInfo> payload = null;
            try {
                payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
            } catch (Exception e) {
                throw new RuntimeException("用户登录已经失效！", e);
            }
            //		3.2.黑名单验证
            Boolean exists = redisTemplate.hasKey(payload.getId());
            if(exists != null && exists){
                // 黑名单中存在
                throw new RuntimeException("用户token在黑名单中，已经失效！");
            }
            //	TODO 4.通过用户获取权限
            UserInfo user = payload.getUserInfo();
            String role = user.getRole();
            //	5.获取当前请求的资源路径
            String requestURI = request.getRequestURI();
            //	TODO 6.判断是否有权限访问
            log.info("用户【{}】, 角色【{}】，正在访问{}资源", user.getUsername(), role, requestURI);
        } catch (RuntimeException e) {
            log.error("非法访问!", e);
            // 拦截访问，没有权限访问
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
        }
        return null;
    }
}
